#include "detaillines.h"

DetailLines::DetailLines(QWidget *parent) : QWidget(parent)
{
    //初始化 坐标系
    mChart = new QChart();
    mAxisX = new QValueAxis(mChart); //X轴
    mAxisY = new QValueAxis(mChart); //Y 轴
    chartInit(mChart,mAxisX,mAxisY);

    //初始化 坐标系容器
    QPalette pal = palette();
    pal.setColor(QPalette::Background, QColor(0x00,0xff,0x00,0x00));

    mChartView = new QChartView(mChart,this);
    mChartView->setPalette(pal);
    mChartView->setRenderHint(QPainter::Antialiasing);  //渲染，曲线不会有锯齿
    QGridLayout *gridLayout = new QGridLayout(this);
    gridLayout->addWidget(mChartView);
}

DetailLines::~DetailLines()
{
    delete mChartView->chart();
}

void DetailLines::chartInit(QChart *chart,QValueAxis *axisX,QValueAxis *axisY)
{
    axisX->setRange(0, 23);             //设置坐标轴范围
    axisX->setTitleText("时间（时）");  //标题
    axisX->setLabelFormat("%d");        //标签格式：每个单位保留几位小数
    axisX->setLabelsAngle(0);
    axisX->setTickCount(24);            //主分隔个数：0到10分成20个单位
    //axisX->setMinorTickCount(2);        //每个单位之间绘制了多少虚网线(次网格)
    axisX->setMinorGridLineVisible(false);
    axisX->setGridLineVisible(true);

    axisY->setRange(0, 10000);
    //axisY->setTitleFont(QFont());
    axisY->setTitleText("操作量（次）");
    axisY->setLabelFormat("%d"); //标签格式
    axisY->setTickCount(6);
    //axisY->setMinorTickCount(2);
    axisY->setMinorGridLineVisible(false);
    axisY->setGridLineVisible(true);

    //设置X、Y轴
    QPen pen;
    pen.setStyle(Qt::SolidLine); pen.setColor(Qt::black);
    axisX->setLinePen(pen);
    axisX->setLineVisible();
    axisY->setLinePen(pen);
    axisY->setLineVisible();

    //为序列设置坐标轴
    chart->setAxisX(axisX);
    chart->setAxisY(axisY);

    chart->setTitle("鼠标、坐标操作详情");
    chart->legend()->hide();    //图例隐藏
}


void DetailLines::appendLine(const QString lineName, QList<QPointF> linePoints, bool isSpline)
{
    QLineSeries *series = nullptr;
    if(mLineHash.contains(lineName))        //曲线已经存在
        series = mLineHash.value(lineName);
    else        //曲线还不存在，新建
    {
        series = isSpline ? new QSplineSeries(mChart) : new QLineSeries(mChart);
        series->setName(lineName);
        series->setPointsVisible(1);    //默认点可见
        mChart->addSeries(series);
        mLineHash.insert(series->name(),series);
        series->attachAxis(mAxisY);
        series->attachAxis(mAxisX);
    }
    if(series)
    {
        series->append(linePoints);
        //矫正坐标系
        int count = series->count();
        int rangMax = mAxisX->max();
        qDebug()<<Q_FUNC_INFO<<"count:"<<count<<"   max:"<<rangMax;
        if(count > rangMax)
        {
            mAxisX->setRange(count-10,count+1);
//            mAxisX->setMin(count-10);
//            mAxisX->setMax(count+1);
            //series->attachAxis(mAxisX);   //只有series已经被添加进chart之后，再执行attachAxis才能有效
        }
    }
}


